using System;
using System.Data;

namespace PS.WebParts.Rollup.Core
{
    class DynamicCorrelateRelation : DataRelation 
    {
        ATabularDataSource dataSource;
        Join.CorrelationType correlationType;

        public DynamicCorrelateRelation(string relationName, DataColumn parentColumn, DataColumn childColumn, ATabularDataSource childDataSource, Join.CorrelationType correlationType)
            : base(relationName, parentColumn, childColumn, false)
        {
            this.dataSource = childDataSource;
            this.correlationType = correlationType;
        }

        private DataTable data;
        public  DataTable GetResultingTable()
        {
            return data;
        }

        public DataRow[] GetChildRows(DataRow row)
        {
            if (correlationType == Join.CorrelationType.None)
                return row.GetChildRows(this);
            else
            {
                object webUrl = row["_SiteUrl"];
                if (webUrl == null)
                    throw new ApplicationException(
                        "Base table did not include a _SiteUrl column. Be sure that the data source control contains IncludeListData=\"True\"");

                if (!(dataSource is RollUpDataSource))
                    throw new ApplicationException(
                        "Correlate-web join type can only be used on the right-hand datasource of type RollUpDataSource and its descendants");

                ((RollUpDataSource)dataSource).TopLevelSite = webUrl.ToString();

                ATabularDataSourceView view = dataSource.GetView();
                view.ForceRollupRerun();
                data = view.GetData();
                DataRowCollection dataRows = data.Rows;
                DataRow[] arr = new DataRow[dataRows.Count];
                dataRows.CopyTo(arr, 0);
                return arr;
            }
        }
    }
}
